<?php 
/**
 * Job foldermanage Class
 * @mawei
 */

require_once(OC::$SERVERROOT . "/apps/company/lib/helper.php");
require_once(OC::$SERVERROOT . "/apps/jobposition/lib/helper.php");

class PJobpositionModelFolder extends JModelLegacy 
{
   /**
    * Save job folder
    * @return boolean
    *
    * @since 3.3
    */
   public function saveFolder() {
      $fid = JRequest::getInt('fid', 0);
      $fname = JRequest::getString('fname', '');
      $type = JRequest::getString('type', 'user');
      $source = JRequest::getString('source', '');
      // $fromsetting joblist page : false , setting page : true;
      $fromsetting = JRequest::getString('fromsetting',false);
   
      if (!PCompanyHelper::isJobManager()) {
         $this->setError('没有权限！');
         return false;
      }
   
      $db = PFactory::getDbo();
   
      if (empty($source)) {
         if (empty($fname)) {
            $this->setError('网络异常，请重试！');
            return false;
         }

         $ftitle = ($type == 'user' ? '文件夹' : '职位组合');

         // _t<integer> is reserved folder name
         if(preg_match("/^_t\d+$/", $fname)) {
            $this->setError('该' . $ftitle . '名禁止使用！');
            return false;
         }

         $query = "SELECT COUNT(*) FROM *PREFIX*hr_job_folder WHERE owner=" . $db->quote(OC_User::getUser()) . " AND folder_name=" . $db->quote($fname) . " AND folder_id!=" . intval($fid) . " AND type=" . $db->quote($type);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if ($db->loadResult()) {
            $this->setError('该' . $ftitle . '已存在！');
            return false;
         }

         if (!$fid) {
            $query = "INSERT INTO *PREFIX*hr_job_folder (folder_name, owner, type, system, created) VALUES (" . $db->quote($fname) . ", " . $db->quote(OC_User::getUser()) . ", " . $db->quote($type) . ", 0, UTC_TIMESTAMP())
                      ON DUPLICATE KEY UPDATE folder_id=LAST_INSERT_ID(folder_id), folder_name=VALUES(folder_name), system=VALUES(system)";
         } else {
            $query = "INSERT INTO *PREFIX*hr_job_folder (folder_id, folder_name, owner, type, system, created) VALUES (" . intval($fid) . ", " . $db->quote($fname) . ", " . $db->quote(OC_User::getUser()) . ", " . $db->quote($type) . ", 0, UTC_TIMESTAMP())
                      ON DUPLICATE KEY UPDATE folder_id=LAST_INSERT_ID(folder_id), folder_name=VALUES(folder_name), system=VALUES(system)";
         }
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute()) {
            $this->setError($ftitle . (empty($fid) ? '创建失败！' : '更新失败！'));
            return false;
         }
      } else {
         if ($source == 'jobgroup_internal') {
            $fname = $type . '_internal';
         } elseif ($source == 'jobgroup_custom') {
            $fname = '常用组合';
         } elseif ($source == 'autorenewjobs') {
            $fname = '自动刷新';
         } else {
            $this->setError('系统错误！');
            return false;
         }
         $data = '';
         $cityids = json_decode(JRequest::getString('cityids', '[]'));
         $folderid = JRequest::getString('folderid', '');
         if (!empty($cityids)) {
            $data['cityids'] = $cityids;
            $data['custom'] = false;
         }
         if(!empty($folderid)){
            $data['folderid'] = $folderid;
            $data['custom'] = false;
         }

         if(!empty($data)){
            $data = json_encode($data);
         }else{
            if($source == 'autorenewjobs' && empty($cityids) && empty($folderid)){
               $syncsource = explode('_', $type);
               if(count($syncsource) <=1)
                  return false;
   
               if(!$fromsetting){
                  $autorenewtype = 'autorenewjobs_'.$syncsource[1];
                  $query = "SELECT data FROM *PREFIX*hr_job_folder WHERE owner = " . $db->quote(OC_User::getUser()) . " AND type = ".$db->quote($autorenewtype);
                  $db->setQuery(PUtil::replaceOCPrefix($query));
                  $result =  $db->loadAssoc();
                  if(isset($result['data'])){
                     $newdata = json_decode($result['data'],true);
                     $newdata['custom'] = true;
                     $data = json_encode($newdata);
                  }else{
                     $data['custom'] = true;
                     $data = json_encode($data);
                  }
               }else{
                  $data['custom'] = true;
                  $data = json_encode($data);
               }
            }
         }

         $query = "INSERT INTO *PREFIX*hr_job_folder (folder_name, owner, type, system, data, created) VALUES (" . $db->quote($fname) . ", " . $db->quote(OC_User::getUser()) . ", " . $db->quote($type) . ", 1, " . $db->quote($data) . ", UTC_TIMESTAMP())
                  ON DUPLICATE KEY UPDATE folder_id=LAST_INSERT_ID(folder_id), data=VALUES(data), system=VALUES(system)";

         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute()) {
            $this->setError('系统错误！');
            return false;
         }
      }
   
      CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*hr_job_folder'));

      $query = 'SELECT LAST_INSERT_ID()';
      $db->setQuery($db->useLastConnection($query));
      $fid = $db->loadResult();
      if (!$fid) {
         $this->setError('系统错误！');
         return false;
      }

      if ($type == 'reports') {
         # update last jobgroup for reports
         PReportsHelper::updateJobgroup($fid, PFactory::getMasterUser()->id, 'reports');
      }
       
      return $fid;
   }
    
   /**
    * Move jobs in folder
    *
    * @return  boolean
    *
    * @since 3.3
    */
   public function saveInFolder($fid = 0) {
      $fid = empty($fid) ? JRequest::getInt('fid', 0) : $fid;
      $jobids = json_decode(JRequest::getString("ids", "[]"));
      $syncsource = JRequest::getString('syncsource','');
      $fromsetting = JRequest::getString('fromsetting',false);
   
      if(empty($fid) || empty($jobids)) {
         $this->setError('网络异常，请重试！');
         return false;
      }
   
      if (!PCompanyHelper::isJobManager()) {
         $this->setError('没有权限！');
         return false;
      }
       
      $db = PFactory::getDbo();
      JArrayHelper::toInteger($jobids);

      $query = "SELECT type,data FROM *PREFIX*hr_job_folder WHERE folder_id=" . intval($fid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $result = $db->loadAssoc();
      if (empty($result['type'])) {
         $this->setError('文件夹或职位组合不存在！');
         return false;
      }else{
         $type = $result['type'];
      }

      if(isset($result['data'])){
         $data = json_decode($result['data'],true);
         if(isset($data['custom']) &&  $data['custom'] == true  && !$fromsetting){
            $cityjobids = array();
            $folderjobids = array();
            $customjobids = array();
            if(empty($syncsource))
               return false;
            $master_uid = PFactory::getMasterUser()->get("id");
            if(isset($data['cityids']) && !empty($data['cityids'])){
               $jobList = PResumesHelper::getJobList($master_uid, 0, '', $data['cityids'][0], '',$syncsource);
               if(!empty($jobList)){
                  foreach($jobList as $val){
                     $cityjobids[] = $val['id'];
                  }
               }
            }elseif (isset($data['folderid']) && !empty($data['folderid'])){
               if($data['folderid'] == '-1'){
                  $jobList = PResumesHelper::getJobList($master_uid, 0, '', '', '',$syncsource);
                  if(!empty($jobList)){
                     foreach($jobList as $val){
                        $folderjobids[] = $val['id'];
                     }
                  }
               }else{
                  $query = "SELECT ff.job_id FROM *PREFIX*hr_job_folder_files ff LEFT JOIN #__jobs_job j ON j.id = ff.job_id
                            WHERE ff.folder_id = ".intval($data['folderid'])." AND LOCATE(".$db->quote($syncsource).", j.source) > 0  ";
                  $db->setQuery(PUtil::replaceOCPrefix($query));
                  $result = $db->loadAssocList();
                  if(!empty($result)){
                     foreach($result as $val){
                        $folderjobids[] = $val['job_id'];
                     }
                  }
               }
            }

            if(isset($data['cityids']) || isset($data['folderid'])){
               $newdata = array();
               $newdata['custom'] = true;
               $newdata = json_encode($newdata);
               $query = "UPDATE *PREFIX*hr_job_folder SET data = ".$db->quote($newdata)." WHERE owner=" . $db->quote(OC_User::getUser()) . " AND folder_id = ".intval($fid);
               $db->setQuery(PUtil::replaceOCPrefix($query));
               if (!$db->execute()) {
                  $this->setError('系统错误！');
                  return false;
               }
            }

            $query = "SELECT ff.job_id FROM *PREFIX*hr_job_folder_files ff LEFT JOIN #__jobs_job j ON j.id = ff.job_id
                               WHERE ff.folder_id = ".intval($fid)." AND LOCATE(".$db->quote($syncsource).", j.source) > 0  ";
            $db->setQuery(PUtil::replaceOCPrefix($query));
            $result = $db->loadAssocList();
            if(!empty($result)){
               foreach($result as $val){
                  $customjobids[] = $val['job_id'];
               }
            }
            $jobids = array_unique(array_merge($jobids,$cityjobids,$folderjobids,$customjobids));
         }
      }

      if ($type == 'user') {
         // get related folderids
         $query = "SELECT DISTINCT hjf.folder_id FROM *PREFIX*hr_job_folder_files AS hjff " .
                  " LEFT JOIN *PREFIX*hr_job_folder AS hjf ON hjf.folder_id=hjff.folder_id " .
                  " WHERE hjf.type='user' AND hjf.system=0 AND hjf.owner=" . $db->quote(OC_User::getUser()) . " AND hjff.job_id IN (" . implode(",", $jobids) . ")";
         $db->setQuery(PUtil::replaceOCPrefix($query));
         $relatedFolderids = $db->loadAssocList('', 'folder_id');
         $relatedFolderids = $relatedFolderids ? $relatedFolderids: array();
      
         if (!in_array($fid, $relatedFolderids)) {
            array_push($relatedFolderids, $fid);
         }
      
         // move jobs from other folder
         $query = "UPDATE *PREFIX*hr_job_folder_files AS hjff " .
                  " LEFT JOIN *PREFIX*hr_job_folder AS hjf ON hjf.folder_id=hjff.folder_id " .
                  " SET hjff.folder_id=" .intval($fid) .
                  " WHERE hjf.type='user' AND hjf.system=0 AND hjf.owner=" . $db->quote(OC_User::getUser()) . " AND hjff.folder_id!=" . intval($fid) . " AND hjff.job_id IN (" . implode(",", $jobids) . ")";
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute()) {
            $this->setError('移动职位失败！');
            return false;
         }
      } else {
         $relatedFolderids = array($fid);
         $query = "SELECT hjff.job_id FROM *PREFIX*hr_job_folder_files AS hjff " .
                  " LEFT JOIN *PREFIX*hr_job_folder AS hjf ON hjf.folder_id=hjff.folder_id " .
                  " WHERE hjf.owner=" . $db->quote(OC_User::getUser()) . " AND hjff.folder_id=" . intval($fid);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         $curJobids = $db->loadAssocList('', 'job_id');
         $delJobids = array_diff($curJobids, $jobids);
         if (!empty($delJobids)) {
            $query = "DELETE hjff.* FROM *PREFIX*hr_job_folder_files AS hjff " .
                     " LEFT JOIN *PREFIX*hr_job_folder AS hjf ON hjf.folder_id=hjff.folder_id " .
                     " WHERE hjf.owner=" . $db->quote(OC_User::getUser()) . " AND hjff.folder_id=" . intval($fid) . " AND hjff.job_id IN (" . implode(",", $delJobids) . ")";
            $db->setQuery(PUtil::replaceOCPrefix($query));
            if (!$db->execute()) {
               $this->setError('保存组合失败！');
               return false;
            }
         }
      }
      
       
      // add jobs to given folder
      if(!empty($jobids)) {
         $values = array();
         foreach ($jobids as $jid) {
            $values[] = "(" . intval($fid) . ", " . $db->quote($jid) . ")";
         }
   
         $query = "INSERT IGNORE INTO *PREFIX*hr_job_folder_files (folder_id, job_id) VALUES " . implode(",", $values);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         if (!$db->execute()) {
            $this->setError('移动职位失败！');
            return false;
         }
      }
   
      // update total number of related folder
      $query = "UPDATE *PREFIX*hr_job_folder AS jf
                SET jf.num=(SELECT COUNT(*) FROM  *PREFIX*hr_job_folder_files AS f LEFT JOIN #__jobs_job AS jj ON jj.id=f.job_id WHERE f.folder_id=jf.folder_id AND jj.is_trashed=0)
                WHERE jf.folder_id IN (" . implode(",", $relatedFolderids) . ")";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();
   
      CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*hr_job_folder', '*PREFIX*hr_job_folder_files'));
       
      return true;
   }
    
   /**
    * Remove job folder
    * @return boolean
    *
    * @since 3.3
    */
   public function removeFolder() {
      $fid = JRequest::getInt('fid', 0);
       
      if (empty($fid)) {
         $this->setError('网络异常，请重试！');
         return false;
      }
   
      if (!PCompanyHelper::isJobManager()) {
         $this->setError('没有权限！');
         return false;
      }
       
      $db = PFactory::getDbo();

      $query = "SELECT type FROM *PREFIX*hr_job_folder WHERE folder_id=" . intval($fid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $type = $db->loadResult();
      if (empty($type)) {
         $this->setError('文件夹或职位组合不存在！');
         return false;
      }
      $ftitle = ($type == 'user' ? '文件夹' : '职位组合');
      
      // only allow system=0 deletion 
      $query = "SELECT COUNT(*) FROM *PREFIX*hr_resume_folder WHERE system!=0 AND owner=" . $db->quote(OC_User::getUser()) . " AND folder_id=" . intval($fid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if($db->loadResult() > 0) {
         $this->setError('该' . $ftitle . '不能删除！');
         return false;
      }
 
      $query = "DELETE jff.* FROM *PREFIX*hr_job_folder_files AS jff
                LEFT JOIN *PREFIX*hr_job_folder jf ON jf.folder_id=jff.folder_id WHERE jf.owner=" . $db->quote(OC_User::getUser()) . " AND jff.folder_id=" . intval($fid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
   
      $query = "DELETE FROM *PREFIX*hr_job_folder WHERE owner=" . $db->quote(OC_User::getUser()) . " AND folder_id=" . intval($fid);
      $db->setQuery(PUtil::replaceOCPrefix($query));
      if (!$db->execute())
         return false;
   
      CacheHelper::triggerRemove(OC_User::getUser(), array('*PREFIX*hr_job_folder'));
       
      return true;
   }
}
